package com.ruoyi.SuveryInterface.SuveryUtils.util;

import com.alibaba.fastjson.JSON;
import com.google.common.net.MediaType;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * Created by rwy-mark on 2017/5/18.
 */
public class HttpClientUtils {
	private static Log logger = LogFactory.getLog(HttpClientUtils.class);

	private final static String CONTENT_TYPE_APPLICATION_JSON=MediaType.JSON_UTF_8.toString();

	private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
	private static CloseableHttpClient httpClient = null;
	private static final int DEFAULT_MAX_TOTAL_CONNECTION = 1024;
	private static final int DEFAULT_MAX_PER_ROUTE = 300;
	private static final String DEFAULT_ENCODING = "UTF-8"; // 默认的查询参数及返回结果的字符串编码
	private static final String CONTENT_TYPE_TEXT_XML = "application/xml"; // 默认的查询参数及返回结果的字符串编码
	private static final String APPLICATION_XML = "text/xml"; // 默认的查询参数及返回结果的字符串编码
	private static final int DEFAULT_CONNECTION_TIME_OUT = 60000; // 默认连接超时时间,
																	// 60秒
	private static final int DEFAULT_READ_TIME_OUT = 60000; // 默认响应超时时间, 60秒

	static {
		LogUtil.writeLog("初始化開始:");
		poolingHttpClientConnectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTION);
		poolingHttpClientConnectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
		httpClient = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
		LogUtil.writeLog("初始化結束:");
	}

	private HttpClientUtils() {
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String invokeGet(String url, Map<String, String> params) {
		return invokeGet(url, params, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String szylPost(String url, Map<String, String> params) {
		return szylPost(url, params, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String ysPost(String url, String params) {
		return ysPost(url, params, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String mpPost(String url, String params) {
		return mpPost(url, params, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String jaPost(String url, String params) {
		return jaPost(url, params, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * 长沙松顺 运营商三要素
	 * @param url
	 * @param params
	 * @return
	 */
	public static String csssPost(String url, List<NameValuePair> parameters) {
		return csssPost(url, parameters, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * 鲸安 身份证人像二要素
	 * @param url
	 * @param params
	 * @return
	 */
	public static String jaFacePost(String url, HttpEntity entity) {
		return jaFacePost(url, entity, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String tyPost(String url, String params) {
		return tyPost(url, params, CONTENT_TYPE_APPLICATION_JSON, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String yjPost(String url, String params) {
		return yjPost(url, params, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	/**
	 * @param url
	 * @param params
	 * @param encode
	 * @param connectTimeout
	 * @param readTimeout
	 * @return
	 */
	public static String szylPost(String url, Map<String, String> params, String encode, int connectTimeout,
			int readTimeout) {
		if (connectTimeout <= 0) {
			return null;
		}
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
				.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build();
		String responseString;
		// 封装请求参数
		List<NameValuePair> formParams = new ArrayList<NameValuePair>();
		if (params != null) {
			Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, String> entry = it.next();
				BasicNameValuePair nameValue = new BasicNameValuePair(entry.getKey(), entry.getValue());
				formParams.add(nameValue);
			}
		}
		HttpPost httpGet = new HttpPost(url);
		UrlEncodedFormEntity ueEntity = new UrlEncodedFormEntity(formParams, Charset.forName("UTF-8"));
		httpGet.setHeader("Connection", "close");
		httpGet.setConfig(requestConfig);
		httpGet.setEntity(ueEntity);
		responseString = doSzylRequest(httpGet, encode);
		return responseString;
	}

	/**
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 */
	public static String ysPost(String url, String jsonReq, String encode, int connectTimeout, int readTimeout) {
		if (connectTimeout <= 0) {
			return null;
		}
		String responseString = null;
		HttpPost httpGet = null;
		CloseableHttpResponse response = null;
		try {
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(readTimeout)
					.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
			httpGet = new HttpPost(url);
			httpGet.setHeader("Connection", "close");
			httpGet.setConfig(requestConfig);
			StringEntity entity = new StringEntity(jsonReq, "utf-8");// 解决中文乱码问题
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			httpGet.setEntity(entity);
			response = httpClient.execute(httpGet);

			try {
				HttpEntity respEntity = response.getEntity();
				try {
					if (respEntity != null) {
						responseString = EntityUtils.toString(respEntity, encode);
					}
				} finally {
					if (respEntity != null) {
						respEntity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s", httpGet.getURI()),
						e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s", httpGet.getURI()),
					e);
			responseString = "";
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			httpGet.releaseConnection();
		}

		return responseString;
	}


	/**
	 *  微模式post
	 */
	public static String mpPost(String url, String jsonReq, String encode, int connectTimeout, int readTimeout) {
		if (connectTimeout <= 0) {
			return null;
		}
		String responseString = null;
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		try {
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(readTimeout)
					.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
			httpPost = new HttpPost(url);
			httpPost.setHeader("Connection", "Keep-Alive");
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			httpPost.setHeader("Charset", "UTF-8");
			httpPost.setConfig(requestConfig);
			StringEntity entity = new StringEntity(jsonReq, "utf-8");// 解决中文乱码问题
			entity.setContentEncoding("UTF-8");
//			entity.setContentType("application/json");
			httpPost.setEntity(entity);
			response = httpClient.execute(httpPost);

			try {
				HttpEntity respEntity = response.getEntity();
				try {
					if (respEntity != null) {
						responseString = EntityUtils.toString(respEntity, encode);
					}
				} finally {
					if (respEntity != null) {
						respEntity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s", httpPost.getURI()),
						e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s", httpPost.getURI()),
					e);
			responseString = "";
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			httpPost.releaseConnection();
		}

		return responseString;
	}

	/**
	 * 长沙松顺 post
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 */
	public static String csssPost(String url, List<NameValuePair> parameters, String encode, int connectTimeout, int readTimeout) {
		if (connectTimeout <= 0) {
			return null;
		}
		String responseString = null;
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		try {
			URL url1 = new URL(url);
			URI uri = new URI(url1.getProtocol(), url1.getUserInfo(), url1.getHost(), url1.getPort(), url1.getPath(), url1.getQuery(), (String) null);
			httpPost = new HttpPost(uri);

			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(readTimeout)
					.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
			httpPost.setConfig(requestConfig);
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, encode);
			httpPost.setEntity(formEntity);
			response = httpClient.execute(httpPost);

			try {
				HttpEntity respEntity = response.getEntity();
				try {
					if (respEntity != null) {
						responseString = EntityUtils.toString(respEntity, encode);
					}
				} finally {
					if (respEntity != null) {
						respEntity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s", httpPost.getURI()),
						e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s", httpPost.getURI()),
					e);
			responseString = "";
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		} finally {
			httpPost.releaseConnection();
		}

		return responseString;
	}


	/**
	 * 鲸安post
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 */
	public static String jaPost(String url, String jsonReq, String encode, int connectTimeout, int readTimeout) {
		if (connectTimeout <= 0) {
			return null;
		}
		String responseString = null;
		HttpPost httpGet = null;
		CloseableHttpResponse response = null;
		try {
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(readTimeout)
					.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
			httpGet = new HttpPost(url);
			httpGet.setHeader("xa-key", "zOyducNb7gYwkcaOUaCXPUDhRZYQ0q6R1+NniijwsdU=");
			httpGet.setConfig(requestConfig);
			StringEntity entity = new StringEntity(jsonReq, "utf-8");// 解决中文乱码问题
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			httpGet.setEntity(entity);
			response = httpClient.execute(httpGet);

			try {
				HttpEntity respEntity = response.getEntity();
				try {
					if (respEntity != null) {
						responseString = EntityUtils.toString(respEntity, encode);
					}
				} finally {
					if (respEntity != null) {
						respEntity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s", httpGet.getURI()),
						e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s", httpGet.getURI()),
					e);
			responseString = "";
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			httpGet.releaseConnection();
		}

		return responseString;
	}

	/**
	 * 鲸安 人像 post
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 */
	public static String jaFacePost(String url, HttpEntity entity, String encode, int connectTimeout, int readTimeout) {
		if (connectTimeout <= 0) {
			return null;
		}
		String responseString = null;
		HttpPost httpGet = null;
		CloseableHttpResponse response = null;
		try {
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(readTimeout)
					.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
			httpGet = new HttpPost(url);
			httpGet.setHeader("xa-key", "zOyducNb7gYwkcaOUaCXPUDhRZYQ0q6R1+NniijwsdU=");
			httpGet.setConfig(requestConfig);
			httpGet.setEntity(entity);
			response = httpClient.execute(httpGet);

			try {
				HttpEntity respEntity = response.getEntity();
				try {
					if (respEntity != null) {
						responseString = EntityUtils.toString(respEntity, encode);
					}
				} finally {
					if (respEntity != null) {
						respEntity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s", httpGet.getURI()),
						e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s", httpGet.getURI()),
					e);
			responseString = "";
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			httpGet.releaseConnection();
		}

		return responseString;
	}

	/**
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 */
	public static String yjPost(String url, String jsonReq, String encode, int connectTimeout, int readTimeout) {
		try {
			URL obj = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
			conn.setConnectTimeout(connectTimeout);
			conn.setReadTimeout(readTimeout);
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
            conn.setDoInput(true);
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(jsonReq);
            out.flush();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encode));
			StringBuffer response = new StringBuffer();

			String line;
			while ((line = br.readLine()) != null) {
				response.append(line);
			}
			br.close();
			return response.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * @param httpRequestBase
	 * @param encode
	 * @return
	 */
	private static String doSzylRequest(HttpRequestBase httpRequestBase, String encode) {

		String responseString = null;
		try {
			long start = System.currentTimeMillis();
			CloseableHttpResponse response = httpClient.execute(httpRequestBase);
			logger.info("HttpClientUtils Begin Invoke: " + httpRequestBase.getURI() + ", cost time "
					+ (System.currentTimeMillis() - start) + " ms");
			try {
				HttpEntity entity = response.getEntity();
				try {
					if (entity != null) {
						responseString = EntityUtils.toString(entity, encode);
					}
				} finally {
					if (entity != null) {
						entity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s",
						httpRequestBase.getURI()), e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s",
					httpRequestBase.getURI()), e);
			responseString = "";
		} catch (Exception e) {
			logger.error(
					String.format("[HttpClientUtils.doRequest] invoke get error, url:%s", httpRequestBase.getURI()), e);
			responseString = "";
		} finally {
			httpRequestBase.releaseConnection();
		}
//		logger.info("HttpClientUtils response : " + responseString);
		return responseString;
	}

	/**
	 * @param url
	 * @param params
	 * @param encode
	 * @param connectTimeout
	 * @param readTimeout
	 * @return
	 */
	public static String invokeGet(String url, Map<String, String> params, String encode, int connectTimeout,
			int readTimeout) {
		if (connectTimeout <= 0) {
			return null;
		}
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
				.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build();
		String responseString;
		String requestUrl;
		try {
			requestUrl = buildRequestUrl(url, params);
		} catch (UnsupportedEncodingException e) {
			logger.error("encode http get params error, params is " + params, e);
			return "";
		}
		HttpPost httpGet = new HttpPost(requestUrl);
		httpGet.setHeader("Connection", "close");
		httpGet.setConfig(requestConfig);
		responseString = doRequest(httpGet, encode);
		return responseString;
	}

	/**
	 * @param requestUrl
	 * @param params
	 * @return
	 */
	public static String invokePost(String requestUrl, Map<String, Object> params) {
		return invokePost(requestUrl, params, null, null, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT,
				DEFAULT_READ_TIME_OUT);
	}
	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String lrPost(String url, Map<String, Object> params) {
		return lrPost(url, params, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}
	/**
	 * @param requestUrl
	 * @param requestHeader
	 * @param requestBody
	 * @return
	 */
	public static String invokePost(String requestUrl, Map<String, String> requestHeader, String requestBody) {
		return invokePost(requestUrl, null, requestHeader, requestBody, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT,
				DEFAULT_READ_TIME_OUT);
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 */
	public static String yuanShuPost(String url,String body,Map<String, String> params) {
		return yuanShuPost(url,body, params, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}
	//
	// /**
	// * @param requestUrl
	// * @param requestBody
	// * @return
	// */
	// public static String invokePostByJsonEntity(String requestUrl, String
	// requestBody) {
	// return invokePost(requestUrl, null, JSON_HEADER, requestBody,
	// DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	// }

	/**
	 * @param requestUrl
	 * @param params
	 * @param requestHeader
	 * @param requestBody
	 * @param encode
	 * @param connectTimeout
	 * @param readTimeout
	 * @return
	 */
	public static String invokePost(String requestUrl, Map<String, Object> params, Map<String, String> requestHeader,
			String requestBody, String encode, int connectTimeout, int readTimeout) {
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
				.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build();
		String responseString;
		HttpPost httpPost = new HttpPost(requestUrl);
		httpPost.setConfig(requestConfig);

		if (MapUtils.isNotEmpty(requestHeader)) {
			for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
				httpPost.addHeader(entry.getKey(), entry.getValue());
			}
		}

		buildPostParams(httpPost, params, requestBody, encode);
		responseString = doRequest(httpPost, encode);
		return responseString;
	}

	/**
	 * @param httpPost
	 * @param params
	 * @param requestBody
	 * @param encode
	 */
	private static void buildPostParams(HttpPost httpPost, Map<String, Object> params, String requestBody,
                                        String encode) {
		try {
			if (MapUtils.isNotEmpty(params)) {
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

				for (Map.Entry<String, Object> entry : params.entrySet()) {
					String value = null;
					if (entry.getValue() instanceof String) {
						value = (String) entry.getValue();
					} else {
						value = JSON.toJSONString(entry.getValue());
					}
					nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value));
				}

				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, encode));
			}

			if (StringUtils.isNotBlank(requestBody)) {
				httpPost.setEntity(new StringEntity(requestBody, encode));
			}

		} catch (UnsupportedEncodingException e) {
			logger.error("HttpClientUtils.buildPostParams error, params = " + params, e);
		}
	}

	/**
	 * @param httpRequestBase
	 * @param encode
	 * @return
	 */
	private static String doRequest(HttpRequestBase httpRequestBase, String encode) {
		String responseString = null;
		try {
			long start = System.currentTimeMillis();
			CloseableHttpResponse response = httpClient.execute(httpRequestBase);
			logger.info("HttpClientUtils Begin Invoke: " + httpRequestBase.getURI() + ", cost time "
					+ (System.currentTimeMillis() - start) + " ms");
			try {
				HttpEntity entity = response.getEntity();
				try {
					if (entity != null) {
						responseString = EntityUtils.toString(entity, encode);
					}
				} finally {
					if (entity != null) {
						entity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s",
						httpRequestBase.getURI()), e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s",
					httpRequestBase.getURI()), e);
			responseString = "";
		} catch (Exception e) {
			logger.error(
					String.format("[HttpClientUtils.doRequest] invoke get error, url:%s", httpRequestBase.getURI()), e);
			responseString = "";
		} finally {
			httpRequestBase.releaseConnection();
		}
		logger.info("HttpClientUtils response : " + responseString);

		return responseString;
	}

	/**
	 * @param url
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static String buildRequestUrl(String url, Map<String, String> params) throws UnsupportedEncodingException {
		if (CollectionUtils.isEmpty(params)) {
			return url;
		}
		StringBuilder requestUrl = new StringBuilder();
		requestUrl.append(url);
		int i = 0;
		for (Map.Entry<String, String> entry : params.entrySet()) {
			if (i == 0) {
				requestUrl.append("?");
			}
			requestUrl.append(entry.getKey());
			requestUrl.append("=");
			String value = entry.getValue();
			requestUrl.append(URLEncoder.encode(value, "UTF-8"));
			requestUrl.append("&");
			i++;
		}
		requestUrl.deleteCharAt(requestUrl.length() - 1);
		return requestUrl.toString();
	}

	public static boolean canWxPay(HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
		if (userAgent == null || userAgent.indexOf("MicroMessenger/") == -1) {
			return false;
		}
		String version = StringUtils.substringAfter(userAgent, "MicroMessenger/").substring(0, 3); // MicroMessenger/5.0
		Float srcVersion = Float.parseFloat(version);
		Float targetVersion = 5.0f;
		return srcVersion > targetVersion;
	}
    public static void setStringParams(HttpPost httpost,
                                       Map<String, String> params) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
        	LogUtil.writeErrorLog(e.getMessage(), e);
        }
    }

	public static String jiXinPost(String reqUrl, byte[] str) {
		return jiXinPost(reqUrl, str, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT, DEFAULT_READ_TIME_OUT);
	}

	public static String jiXinPost(String url, byte[] reponse, String encode, int connectTimeout, int readTimeout) {
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
				.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build();
		String responseString;
		String resp = new String(reponse, Charset.forName("UTF-8"));
		HttpPost httpGet = new HttpPost(url);
		StringEntity entity = new StringEntity(resp, "utf-8");// 解决中文乱码问题
		httpGet.setConfig(requestConfig);
		httpGet.setEntity(entity);
		responseString = doSzylRequest(httpGet, encode);
		return responseString;
	}
	/**
	 * @param url
	 * @param params
	 * @param encode
	 * @param connectTimeout
	 * @param readTimeout
	 * @return
	 */
	public static String lrPost(String url, Map<String, Object> params, String encode, int connectTimeout,
			int readTimeout) {
		   PoolingHttpClientConnectionManager connManager = null ;
		try {
			SSLContext sslcontext = createIgnoreVerifySSL();
			 SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		        // 设置协议http和https对应的处理socket链接工厂的对象
		        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
		            .register("http", PlainConnectionSocketFactory.INSTANCE)
		            .register("https",sslFactory)
		            .build();
		         connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
				 connManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTION);
				 connManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
		        HttpClients.custom().setConnectionManager(connManager);
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
				.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build();
		String responseString;
		// 封装请求参数
		List<NameValuePair> formParams = new ArrayList<NameValuePair>();
		if (params != null) {
			Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, Object> entry = it.next();
				BasicNameValuePair nameValue = new BasicNameValuePair(entry.getKey(), (String) entry.getValue());
				formParams.add(nameValue);
			}
		}

		HttpPost httpGet = new HttpPost(url);
		UrlEncodedFormEntity ueEntity = new UrlEncodedFormEntity(formParams, Charset.forName("UTF-8"));
		httpGet.setConfig(requestConfig);
		httpGet.setEntity(ueEntity);
		responseString = doLrRequest(httpGet, encode, connManager);
		return responseString;
	}
	  /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    private static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }
	private static String doLrRequest(HttpRequestBase httpRequestBase, String encode, PoolingHttpClientConnectionManager connManager) {

		String responseString = null;
		try {
			long start = System.currentTimeMillis();
			CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
			CloseableHttpResponse response = client.execute(httpRequestBase);
			logger.info("HttpClientUtils Begin Invoke: " + httpRequestBase.getURI() + ", cost time "
					+ (System.currentTimeMillis() - start) + " ms");
			try {
				HttpEntity entity = response.getEntity();
				try {
					if (entity != null) {
						responseString = EntityUtils.toString(entity, encode);
					}
				} finally {
					if (entity != null) {
						entity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s",
						httpRequestBase.getURI()), e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s",
					httpRequestBase.getURI()), e);
			responseString = "";
		} catch (Exception e) {
			logger.error(
					String.format("[HttpClientUtils.doRequest] invoke get error, url:%s", httpRequestBase.getURI()), e);
			responseString = "";
		} finally {
			httpRequestBase.releaseConnection();
		}
		logger.info("HttpClientUtils response : " + responseString);

		return responseString;
	}
	/**
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 */
	private static String yuanShuPost(String url, String body,Map<String, String> headers, String encode, int connectTimeout, int readTimeout) {
	HttpURLConnection connection = null;
    InputStream is = null;
    OutputStream os = null;
    BufferedReader br = null;
    String result = null;
    try {
        URL httpUrl = new URL(url);
        connection = (HttpURLConnection) httpUrl.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        for(Map.Entry<String,String> entry : headers.entrySet()){
            connection.setRequestProperty(entry.getKey(),entry.getValue());
        }
        os = connection.getOutputStream();
        os.write(body.getBytes("UTF-8"));
        if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");
            }
            result = sbf.toString();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭资源
        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != os) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        connection.disconnect();
    	}
    	return result;
	}

	 /**
	    *
	    * @param httpRequest
	    * @param entity
	    * @param
	    * @return
	    */
		private static String sendRequest(HttpRequestBase httpRequest, HttpEntity entity) {

			httpRequest.setHeader("User-Agent","okHttp");
	        if(httpRequest instanceof HttpEntityEnclosingRequestBase){
//	            checkArgument(null!=entity,"HttpEntity请求体不能为空");
	            ((HttpEntityEnclosingRequestBase)httpRequest).setEntity(entity);
	        }

	        //忽略证书
	        SSLContext sslContext = SSLContexts.createDefault();

	        X509TrustManager tm = new X509TrustManager() {
	            public void checkClientTrusted(X509Certificate[] xcs,
	                                           String string) throws CertificateException {
	            }

	            public void checkServerTrusted(X509Certificate[] xcs,
	                                           String string) throws CertificateException {
	            }

	            public X509Certificate[] getAcceptedIssuers() {
	                return null;
	            }
	        };

	        try {
	            sslContext.init(null, new TrustManager[]{tm}, null);
	        }
	        catch (Exception ex) {
	            ex.printStackTrace();
	        }

	        X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
	        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

	        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
	                .register("https", sslsf)
	                .build();

	        HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
	        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();


	        CloseableHttpResponse response = null;
	        String resString=null;
	        try {
	            response = httpClient.execute(httpRequest);
	            HttpEntity resEntity = response.getEntity();
	            int statusCode = response.getStatusLine().getStatusCode();
	            resString= EntityUtils.toString(resEntity,"UTF-8");
	            System.err.println(statusCode);
	           if(statusCode!= HttpStatus.SC_OK){
	               System.out.println("响应码状态不是200");
	           }
	            return resString;
	        } catch (Exception e) {
	            throw new RuntimeException(resString, e);
	        } finally {
	            try {
	                if (response != null) {
	                        response.close();
	                }
	                if (httpRequest != null) {
	                    httpRequest.releaseConnection();
	                }
	                if (httpClient != null) {
	                        httpClient.close();
	                }
	            } catch (IOException e) {
	                throw new RuntimeException(e);
	            }
	        }
	    }
		/**
		 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
		 */
		public static String tyPost(String url, String jsonReq, String encode, int connectTimeout, int readTimeout) {
			if (connectTimeout <= 0) {
				return null;
			}
			String responseString = null;
			HttpPost httpGet = null;
			CloseableHttpResponse response = null;
			try {
				RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(readTimeout)
						.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
				httpGet = new HttpPost(url);
				httpGet.setHeader("Connection", "close");
				httpGet.setConfig(requestConfig);
				StringEntity entity = new StringEntity(jsonReq, "utf-8");// 解决中文乱码问题
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				httpGet.setEntity(entity);

				 responseString=sendRequest(httpGet,entity);
//				response = httpClient.execute(httpGet);

				try {
				} catch (Exception e) {
					logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s", httpGet.getURI()),
							e);
					responseString = "";
				} finally {
					if (response != null) {
						response.close();
					}
				}
			} catch (SocketTimeoutException e) {
				logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s", httpGet.getURI()),
						e);
				responseString = "";
			} catch (UnsupportedEncodingException e) {
				logger.error(e.getMessage(), e);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			} finally {
				httpGet.releaseConnection();
			}

			return responseString;
		}

	public static String hyPost(String url, Map<String,Object> map, String charset){
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try{
			httpClient = HttpClients.createDefault();
//	    	httpClient =createSSLClientDefault();
			httpPost = new HttpPost(url);
			//设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator iterator = map.entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry<String,Object> elem = (Map.Entry<String, Object>) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(),String.valueOf(elem.getValue())));
			}
			if(list.size() > 0){
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			System.out.println(response.getEntity());
			if(response != null){
				HttpEntity resEntity = response.getEntity();
				if(resEntity != null){
					result = EntityUtils.toString(resEntity,charset);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return result;
	}

	public static String ysfrPost(String url, String xmlReq) {
			return doYsfrPost(url,xmlReq,DEFAULT_ENCODING,DEFAULT_CONNECTION_TIME_OUT,DEFAULT_READ_TIME_OUT);
	}


	public static String doYsfrPost(String url, String xmlReq, String encode, int connectTimeout, int readTimeout) {
		if (connectTimeout <= 0) {
			return null;
		}
		String responseString = null;
		HttpPost httpGet = null;
		CloseableHttpResponse response = null;

		try {
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(readTimeout)
					.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
			httpGet = new HttpPost(url);
			httpGet.setHeader("Connection", "close");
			httpGet.setConfig(requestConfig);
			StringEntity entity = new StringEntity(xmlReq, "utf-8");// 解决中文乱码问题
			entity.setContentEncoding(APPLICATION_XML);
			entity.setContentType(CONTENT_TYPE_TEXT_XML);
			httpGet.setEntity(entity);
			response = httpClient.execute(httpGet);

			try {
				HttpEntity respEntity = response.getEntity();
				try {
					if (respEntity != null) {
						responseString = EntityUtils.toString(respEntity, encode);
					}
				} finally {
					if (respEntity != null) {
						respEntity.getContent().close();
					}
				}
			} catch (Exception e) {
				logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s", httpGet.getURI()),
						e);
				responseString = "";
			} finally {
				if (response != null) {
					response.close();
				}
			}
		} catch (SocketTimeoutException e) {
			logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s", httpGet.getURI()),
					e);
			responseString = "";
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			httpGet.releaseConnection();
		}

		return responseString;
	}
}
